import { computed, CSSProperties, reactive, ref } from "vue";
export const useStyle = (userStyle: CSSProperties) => {
  // 用户样式
  const style = ref(userStyle)
  const newStyle = computed({
    get: () => ({ ...style.value }),
    set: (currentStyle: CSSProperties) => {
      setStyle(currentStyle)
    }
  })

  // 保存旧样式 
  const _oldStatus = ref<CSSProperties>()
  // 设置样式
  const setStyle = (newStyle: CSSProperties, duration = 5000) => {
    // 往复动画
    const recovery = () => {
      style.value = { transition: style.value['transition'], ..._oldStatus.value }
    }
    // 添加动画
    Object.keys(newStyle).forEach(key => {
      if (key == 'transform' && duration > 0) {
        _oldStatus.value = userStyle

        setTimeout(() => {
          recovery()
        }, duration);
      }
      style.value = { ...style.value, ...newStyle }

    })
    return recovery
  }
  // 获取属性的数值
  const getNumber = <K extends keyof CSSProperties>(key: K) => parseInt(String(style.value[key])) ?? 0

  // 获取属性的字符串
  const getStr = <K extends keyof CSSProperties>(key: K) => style.value[key]

  return {
    style,
    setStyle,
    getNumber,
    getStr,
    newStyle
  }


}